package cn.kgc.commons.util;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * <p>添加描述信息</p>
 *
 * @author 王跃
 */
@Component
public class RedisUtil {
    @Resource
    private RedisTemplate<String,Object> redisTemplate;

    public  void set(String key,Object value,long times,TimeUnit timeUnit){
        redisTemplate.opsForValue().set(key,value,times,timeUnit);
    }

    public Object get(String key){
        return redisTemplate.opsForValue().get(key);
    }

    //1cart  2  CartItem  3  1
    public Object get(String key,Object hk){
        return redisTemplate.opsForHash().get(key,hk);
    }
    //保存hash类型的数据
    public void putKey(String key,Object hk,Object hv){
        redisTemplate.opsForHash().put(key,hk,hv);
    }
    //是否有key
    //key  value(hkey,hvalue)  如果不用这个不能判断Hash里面的Key是否存在
    public  boolean hasKey(String key,Object hk){
        return redisTemplate.opsForHash().hasKey(key,hk);
    }
    //根据Key获得hash类型的数据
    public Map<Object,Object> getHash(String key){
        return redisTemplate.opsForHash().entries(key);
    }

    public void deleteHashKey(String cacheKey, Object hk) {
        redisTemplate.opsForHash().delete(cacheKey,hk);
    }



    public long incrment(String key){
        return redisTemplate.opsForValue().increment(key);
    }


    public boolean hasKey(String key){
        return redisTemplate.hasKey(key);
    }

    //分布式锁
    public boolean setIfAbsent(String key,Object value,
                               long times,TimeUnit timeUnit){
        return redisTemplate.opsForValue().setIfAbsent(key, value, times, timeUnit);
    }

    //lua脚本
    private static final String lua="if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1])" +
            "else return 0 end";

    //执行lua脚本,实现分布式锁中删除锁的操作
    public boolean execute(String lockName,String uuid){
        long result = redisTemplate.execute(
                new DefaultRedisScript<Long>(lua,Long.class),
                Arrays.asList(lockName),
                uuid
        ).longValue();
        return result==1;
    }



    public boolean delete(String key){
        return redisTemplate.delete(key);
    }

}